package it.polimi.jita.cp.block.pc;

import it.polimi.jita.cp.block.InputBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class PenaltyCalculatorInputBuilder extends
		InputBuilder<PenaltyCalculatorInput> {

	@Override
	protected PenaltyCalculatorInput createInput() throws IOException {
		PenaltyCalculatorInput input;
		String iFilePath = getOptionValue("-i");

		List<Double> capacityDemand = new ArrayList<>();

		// TODO Log open file
		System.out.println(String.format("Opening file: %s", iFilePath));

		URL url = this.getClass().getClassLoader().getResource(iFilePath);
		InputStream in = url.openStream();
		InputStreamReader isr = new InputStreamReader(in);
		CSVParser csvParser = new CSVParser(isr, CSVFormat.DEFAULT);
		System.out.println(String.format("Reading file: %s", iFilePath));
		for (Iterator<CSVRecord> iterator = csvParser.iterator(); iterator
				.hasNext();) {
			CSVRecord csvRecord = iterator.next();
			Double demand = Double.parseDouble(csvRecord.get(0));
			capacityDemand.add(demand);
		}
		csvParser.close();

		Double systemCapacity = Double.parseDouble(getOptionValue("-sc"));
		Integer vmsNum = Integer.parseInt(getOptionValue("-nc"));
		Double x0 = Double.parseDouble(getOptionValue("-x0"));
		Double x1 = Double.parseDouble(getOptionValue("-x1"));
		String strX2 = getOptionValue("-x2");
		Double x2 = strX2 != null ? Double.parseDouble(strX2) : null;

		input = new PenaltyCalculatorInput(capacityDemand, systemCapacity,
				vmsNum, x0, x1, x2);

		return input;
	}
}
